<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class upyunStringController extends Controller
{

    public function checkString(Request $request){

        $key = env('UPYUN_KEY');

        $secret = md5(env('UPYUN_SECRET'));

        $date = gmdate('D, d M Y H:i:s \G\M\T');

        $data = array(
            'text'=>$request->text,
        );

        $sign = $this->sign($key,$secret, 'POST'
            ,'/api/upyunString',$date);

        $url = 'http://banma.api.upyun.com/text/check?act=spam';
        //return $this->send_post('http://banma.api.upyun.com/text/check?act=spam'
            //,$data,$sign);

        return $this->http_post_json($url,json_encode($data),$sign);
    }

    /**
     * 又拍云签名生成
     * @param $key
     * @param $secret
     * @param $method
     * @param $uri
     * @param $date
     * @param null $policy
     * @param null $md5
     * @return string
     */
    public function sign($key, $secret, $method, $uri, $date, $policy=null, $md5=null)
    {
        $elems = array();
        foreach (array($method, $uri, $date, $policy, $md5) as $v)
        {
            if ($v)
            {
                $elems[] = $v;
            }
        }
        $value = implode('&', $elems);
        $sign = base64_encode(hash_hmac('sha1', $value, $secret, true));
        return 'UPYUN ' . $key . ':' . $sign;
    }

    function send_post($url, $post_data,$sign) {
        $postdata = http_build_query($post_data);
        $options = array(
            'http' => array(
                'method' => 'POST',
                'header' => array(
                    'Authorization:' . $sign,
                    'Content-type:application/x-www-form-urlencoded',
                    'Content-Type: application/json',
                ),
                'content' => $postdata,
                'timeout' => 15 * 60 // 超时时间（单位:s）
            )
        );
        $context = stream_context_create($options);
        return file_get_contents($url, false, $context);
    }

    function http_post_json($url, $jsonStr, $sign)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonStr);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array(
                'Content-Type: application/json; charset=utf-8',
                'Content-Length: ' . strlen($jsonStr),
                'Authorization:' . $sign,
                'Content-type:application/x-www-form-urlencoded',
            )
        );
        $response = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);

        return $response;
    }
}
